package com.learn.sqlSession;

import com.learn.pojo.Configuration;
import com.learn.pojo.MappedStatement;
import com.learn.pojo.User;

import java.lang.reflect.*;
import java.util.List;

/**
 * @author suyafei
 */
public class DefaultSqlSession implements SqlSession {
    private Configuration configuration;
    private SimpleExecutor simpleExecutor = new SimpleExecutor();

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public void update(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        simpleExecutor.update(configuration,mappedStatement,params);
    }

    @Override
    public void delete(String statementId, Object... params) throws Exception {
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        simpleExecutor.delete(configuration,mappedStatement,params);
    }

    @Override
    public void insert(String statementId, Object... params) throws Exception {

        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        simpleExecutor.insert(configuration,mappedStatement,params);
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {
        //调用query方法
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        List<Object> list = simpleExecutor.query(configuration, mappedStatement, params);
        return (List<E>) list;
    }

    /**
     * 使用JDK动态代理为Dao接口生产代理对象，并返回
     * @param mapperClass
     * @param <T>
     * @return
     */
    @Override
    public <T> T getMapper(Class<?> mapperClass) {

        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            /**
             *
             * @param proxy 当前代理对象的引用
             * @param method 当前呗调用方法的引用
             * @param args 传递的参数
             * @return
             * @throws Throwable
             */
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层还是去执行JDBC
                //根据不同情况来调用selectOne或者selectList

                //准备参数1.statementId：sql的唯一标识:namespace.id=接口全限定名.方法名
                    //方法名
                String methodName = method.getName();
                    //接口全限定名
                String className = method.getDeclaringClass().getName();

                String statementId = className +"."+ methodName;

                //2、准备参数2:params:args
                    //获取到当前方法的返回值类型
                Type genericReturnType = method.getGenericReturnType();

                //判断是否进行了 泛型类型参数化
                //获取crud类型
                String crudType = configuration.getMappedStatementMap().get(statementId).getCrudType();
                if (crudType != null) {
                    if (crudType.equals("//select")) {
                        if (genericReturnType instanceof ParameterizedType) {
                            List<Object> objects = selectList(statementId, args);
                            return objects;
                        }else {
                            return selectOne(statementId,args);
                        }

                    } else if (crudType.equals("//insert")) {
                        insert(statementId,args);
                    } else if (crudType.equals("//update")) {
                        update(statementId,args);
                    } else if (crudType.equals("//delete")) {
                        delete(statementId,args);
                    }else {
                        throw new Exception("不是指定的crud类型");
                    }
                }

                return null;
            }
        });
        return (T) proxyInstance;
    }



    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objects = selectList(statementId, params);
        if (objects.size() == 1) {
            return (T) objects.get(0);
        }else {
            throw new RuntimeException("返回结果为空");

        }
    }
}
